package com.zipeng.security.detailservice;

import com.zipeng.system.permission.entity.Permission;
import com.zipeng.system.permission.service.PermissionService;
import com.zipeng.system.user.entity.SysUser;
import com.zipeng.system.user.service.UserService;
import com.zipeng.util.CacheService;
import com.zipeng.util.KeyCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 认证处理类
 * 查询数据库是否有用户
 */
@Slf4j
@Component("customerUserDetailService")
public class CustomerUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private CacheService cacheService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.查询用户信息
        // 缓存的key
        SysUser user = cacheService.getEntityCache(KeyCode.USER_KEY + username, 600L, SysUser.class, () -> userService.getUserByUserName(username));
        //2.用户不存在抛出异常
        if(null == user){
            throw new UsernameNotFoundException("用户名或密码错误!");
        }
        //3.查询用户权限，设置到SysUser 的 authorities 中
        List<Permission> permissions = cacheService.getListCache(KeyCode.PERMISSION_KEY+username, 600L, Permission.class, () -> permissionService.getPermissionListByUserId(user.getId()));
        //4.获取code字段
        List<String> collect = permissions.stream().filter(item -> item != null).map(item -> item.getCode()).collect(Collectors.toList());
        //5.转成数组
        String[] codes  = collect.toArray(new String[collect.size()]);
        //6.把codes转成List<GrantedAuthority>
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(codes);
        //7.设置权限
        user.setAuthorities(authorityList);
        //8.设置用户所有菜单
        user.setPermissionList(permissions);
        return user;
    }
}